package goutils

import (
	"fmt"
	"log"
	"os"
	"path"
	"strconv"
)

var (
	loger          *log.Logger
	loger_enable   bool
	loger_rootpath string
)

func init() {
	loger_enable = false
}

func Init_log(logroot string) {
	loger_enable = false
	loger_rootpath = logroot
	logFile := path.Join(loger_rootpath, "0.log")
	clean_file(10)

	if PathExists(logFile) {
		os.Remove(logFile)
	}
	if f, err := os.Create(logFile); err == nil {
		loger = log.New(f, "", log.Ldate|log.Ltime)
		loger_enable = true
	}
}

func clean_file(count int) {
	for i := count; i >= 0; i-- {
		file := path.Join(loger_rootpath, strconv.Itoa(i)+".log")
		if i == count {
			if PathExists(file) {
				os.Remove(file)
			}
		} else {
			newfile := path.Join(loger_rootpath, strconv.Itoa(i+1)+".log")
			if PathExists(file) {
				if err := os.Rename(file, newfile); err != nil {
					ShowDebug(err)
				}
			}
		}

	}
}

func Log(v ...interface{}) {
	if loger_enable {
		loger.Println(v...)
	}
}

func ShowDebug(v ...interface{}) {
	if Debug {
		fmt.Println(v...)
		if loger_enable {
			loger.Println(v...)
		}
	}
}
